package com.xli.sso.security.handler;

import com.xli.sso.security.identity.LoginUser;
import com.xli.sso.security.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 将用户信息设置到 SecurityContextHolder 中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("token", JwtUtil.createToken((LoginUser) authentication.getPrincipal()));
        response.getWriter().write("{\"code\":\"1\",\"msg\":\"登录成功\"}");
    }
}
